package com.smartbands.manage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartbands.common.entity.User;
import com.smartbands.common.util.JwtUtil;
import com.smartbands.manage.mapper.UserMapper;
import com.smartbands.manage.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author mtf
 * @create 2021-01-29-13:21
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public String login(String userName, String password) {
        if (StringUtils.isAllBlank(userName)) {
            throw new RuntimeException("用户名为空");
        }
        if (StringUtils.isAllBlank(password)) {
            throw new RuntimeException("密码为空");
        }
        User user = baseMapper.selectByName(userName);
        if (null == user) {
            throw new RuntimeException("未查到相关用户信息");
        }
        if (!password.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        //登录完成生成token
        String token = JwtUtil.sign(userName, user.getUserId(), password);
        return token;
    }

    @Override
    public String register(String userName, String password) throws Exception {
        if (StringUtils.isBlank(userName)) {
            throw new Exception("用户名为空");
        }
        if (StringUtils.isAllBlank(password)) {
            throw new Exception("密码为空");
        }
        //验证用户是否注册
        User user = baseMapper.selectByName(userName);
        if(null!=user){
            throw new Exception("该用户已存在");
        }
        User userIns = new User();
        userIns.setName(userName);
        userIns.setUserId(UUID.randomUUID().toString());
        userIns.setPassword(password);
        baseMapper.insert(userIns);
        return "success";
    }

    @Override
    public User getByUserId(String userId) {
        return baseMapper.getByUserId(userId);
    }

}
